import axios from 'axios'
import { useAuthStore } from './store'

const api = axios.create({
  baseURL: 'http://localhost:8000'
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const { token } = useAuthStore.getState()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
      // 添加认证信息到请求头
      config.headers['x-auth-storage'] = localStorage.getItem('auth-storage')
    }
    
    // 如果是 FormData，确保不设置 Content-Type，让浏览器自动设置
    if (config.data instanceof FormData) {
      config.headers['Content-Type'] = 'multipart/form-data'
    }
    
    console.log('Request config:', config)  // 添加调试日志
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  (error) => {
    console.log('Response error:', error)  // 添加调试日志
    if (error.response?.status === 401) {
      useAuthStore.getState().logout()
    }
    return Promise.reject(error)
  }
)

export default api 